<?php


namespace App\Common\Comp;


use App\Common\ElasticSearch\ImSendLog;
use App\Common\Tencent\TLSSigAPI;
use App\Common\Utill\Utill;
use App\Model\FanGroupChat;
use App\Model\ImRecord;
use App\Model\User;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

class ImComp
{
    protected static $Url = "https://console.tim.qq.com/";
    protected static $Version = "v4/";
    protected static $identifier = "administrator"; //管理员权限
    protected static $type = "json";

    protected $resDate;

    public function __construct()
    {
        //初始化返回值
        $this->resDate = ['code' => 200, 'msg' => '', 'data' => []];
    }

    /**
     * 单群聊信息撤回
     *
     * @param $msgKey
     * @param $fromAccount
     * @param $toAccount
     * @param $type
     *
     * @return bool
     */
    public function adminMsgwithdraw($msgKey, $fromAccount, $toAccount)
    {
        try {
            $sign = self::getUserImSig(self::$identifier);
            $AppId = Config::get('TencentConfig.im')['AppID'];
            $address = "openim/admin_msgwithdraw?";
            $random = Utill::get_order_sn_32();
            $url = self::$Url . self::$Version . $address . "sdkappid=$AppId" . "&identifier=" . self::$identifier . "&usersig=$sign" . "&random=$random" . "&contenttype=" . self::$type;
            $params = [
                "From_Account" => $fromAccount,
                "To_Account" => $toAccount,//目标帐号列表,
                "MsgKey" => $msgKey
            ];
            $res = postCurl($url, json_encode($params), [], 1, 2);
            $res = json_decode($res['result'], true);
            Log::info('单聊撤回消息:' . ',来源于' . $fromAccount . ',发送给用户:' . $toAccount . "撤回结果:" . json_encode($res,
                    JSON_UNESCAPED_UNICODE));
        } catch (\Exception $e) {
            Log::error('撤回消息 ：' . $e->getMessage());
            $res = ["ActionStatus" => "FAIL", "ErrorInfo" => json_encode($e->getMessage(), JSON_UNESCAPED_UNICODE), "ErrorCode" => 500];
        }
        return $res;
    }

    /**
     * 获取登陆签名
     * @param $account 纸鸢Id
     * @return string
     */
    public static function getUserImSig($account)
    {
        $config = Config::get('TencentConfig.im');
        try {
            $api = new TLSSigAPI($config['AppID'], $config['SecretKey']);
            $Sig = $api->genUserSig($account);
            return $Sig;
        } catch (\Exception $e) {
            Log::error($e->getMessage());
        }
    }

    /**
     * im群聊消息撤回
     * @param $groupId
     * @param $msgSeqList
     *
     * @return array
     */
    public function groupMsgRecall($groupId, $msgSeqList)
    {
        try {
            $sign = self::getUserImSig(self::$identifier);
            $AppId = Config::get('TencentConfig.im')['AppID'];
            $address = "group_open_http_svc/group_msg_recall?";
            $random = Utill::get_order_sn_32();
            $url = self::$Url . self::$Version . $address . "sdkappid=$AppId" . "&identifier=" . self::$identifier . "&usersig=$sign" . "&random=$random" . "&contenttype=" . self::$type;
            $params = [
                "GroupId" => $groupId,
                "MsgSeqList" => $msgSeqList
            ];
            Log::info('群聊撤回消息:' . "撤回内容:" . json_encode($params,
                    JSON_UNESCAPED_UNICODE));
            $res = postCurl($url, json_encode($params), [], 1, 2);
            $res = json_decode($res['result'], true);
            Log::info('群聊撤回消息:' . "撤回结果:" . json_encode($res,
                    JSON_UNESCAPED_UNICODE));
        } catch (\Exception $e) {
            Log::error('撤回消息 ：' . $e->getMessage());
            $res = ["ActionStatus" => "FAIL", "ErrorInfo" => json_encode($e->getMessage(), JSON_UNESCAPED_UNICODE), "ErrorCode" => 500];
        }
        return $res;
    }

    /**
     * 批量发单聊消息
     * @param $fromAccount //来自的纸鸢号
     * @param $data //要发送的纸鸢号 array
     * @param $content //发送的内容
     * @param int $type //类型 5=状态改变批量发单聊消息  6=系统消息  7=互动消息 8=粉丝团消息 9=活动发放奖励通知
     * @param int $reserved //是否保留 true=是 false=否
     * @return bool
     */
    public function batchSendMsg($fromAccount, $data, $content, $type = 5, $reserved = true)
    {
        try {
            $sign = self::getUserImSig(self::$identifier);
            $AppId = Config::get('TencentConfig.im')['AppID'];
            $address = "openim/batchsendmsg?";
            $random = Utill::get_order_sn_32();
            $url = self::$Url . self::$Version . $address . "sdkappid=$AppId" . "&identifier=" . self::$identifier . "&usersig=$sign" . "&random=$random" . "&contenttype=" . self::$type;

            $params2 = [];
            if (in_array($type, [6, 7, 8])) {//系统消息 粉丝团消息 互动消息
                $contentArr = json_decode($content, true);
                $params2['From_Account'] = $contentArr['sysSendAccount'];
                $params2['MsgLifeTime'] = 604800;
                $content = $contentArr['content'];
            } elseif ($type == 5) {//上线下线
                $params2['MsgLifeTime'] = 0;
            } elseif ($type == 9) {//上线下线
                $params2['MsgLifeTime'] = 0;
            }
            $params = [
                "SyncOtherMachine" => 1,
                "To_Account" => $data,//目标帐号列表,
                "MsgRandom" => rand(10000000, 99999999),
                "MsgBody" => [
                    array(
                        "MsgType" => 'TIMTextElem',
                        "MsgContent" => [
                            'Text' => $content
                        ]
                    )
                ],
                'SendMsgControl' => ["NoUnread"]
            ];
            $params = array_merge($params, $params2);
            //Log::info('发送im信息准备参数检测5--'.$fromAccount,['type'=>$type,'params'=>$params]);
            $res = postCurl($url, json_encode($params), [], 1, 2);
            Log::info('im返回结果检测6', $res);
            $res = json_decode($res['result'], true);
            Log::info('批量发单聊消息类型:' . $type . ',来源于' . $fromAccount . ',发送给用户:' . json_encode($params), $res);
            if ($reserved) {
                self::imDataRecord($type, 0, $fromAccount, $params, $res['ErrorCode'], $res);
            }
            Log::info('消息发送结果:' . $fromAccount . ',步骤2', ['result' => $res]);
            if ($res['ActionStatus'] == "OK") {
                return true;
            }
            return false;
        } catch (\Exception $e) {
            Log::error('批量发单聊消息 ：' . $e->getMessage());
            return false;
        }
    }

    /**
     * im群信息入库
     * @param $type //1=粉丝团加群  2=粉丝团退群  3=初始化进群 4=客服群
     * @param $groupId //自定义群组id
     * @param $account //纸鸢号
     * @param $requestContent //请求的内容
     * @param $resultCode //返回的code
     * @param $resultContent //返回的内容
     * @return bool
     */
    public static function imDataRecord($type, $groupId, $account, $requestContent, $resultCode, $resultContent)
    {
        $model = new ImRecord();
        $model->type = $type;
        if ($groupId) {
            $model->custom_group = $groupId;
            $model->group_chat_id = FanGroupChat::where('group_chat_name', $groupId)->value('id') ?? 0;
        }
        $model->account = $account;
        if ($account) {
            $model->user_id = User::query()->where('account', strval($account))->value('id') ?? 0;
        } else {
            $model->user_id = 0;
        }
        $model->request_content = json_encode($requestContent, JSON_UNESCAPED_UNICODE);
        $model->result_code = $resultCode;
        $model->result_content = json_encode($resultContent, JSON_UNESCAPED_UNICODE);
//        if($model->save()){
//            return true;
//        }
        //im发送记录数据存入es里面
        $imSendLogResult = ImSendLog::insert($model->toArray());
        Log::info('消息发送结果:' . $account . ',步骤1', ['result' => $imSendLogResult]);
        if ($imSendLogResult['code'] == 200) {
            return true;
        }
        $errorInfo['type'] = $model->type;
        $errorInfo['groupId'] = $groupId;
        $errorInfo['account'] = $model->account;
        $errorInfo['user_id'] = $model->user_id;
        $errorInfo['request_content'] = $model->request_content;
        $errorInfo['result_code'] = $model->result_code;
        $errorInfo['result_content'] = $model->result_content;
        Log::error('im群信息入库失败-' . $account, $errorInfo);
        return false;
    }

    /**
     * 发送系统消息
     * @param string $msgType
     * @param string $fromAccount
     * @param string $account
     * @param array $data
     * @return bool
     */
    public function systemMessage($msgType, $fromAccount, $account, $data)
    {
        try {
            $sign = self::getUserImSig(self::$identifier);
            $AppId = Config::get('TencentConfig.im')['AppID'];
            $address = "openim/sendmsg?";
            $random = Utill::get_order_sn_32();
            $url = self::$Url . self::$Version . $address . "sdkappid=$AppId" . "&identifier=" . self::$identifier . "&usersig=$sign" . "&random=$random" . "&contenttype=" . self::$type;
            $params = [
                'SyncOtherMachine' => 1,
                'From_Account' => (string)$fromAccount,
                'To_Account' => (string)$account,
                'MsgRandom' => rand(100000, 999999),
                'MsgTimeStamp' => time(),
                'MsgBody' => [
                    [
                        'MsgType' => $msgType,
                        'MsgContent' => $data,
                    ]
                ],
            ];

            $res = postCurl($url, json_encode($params), [], 1, 2);
            $res = json_decode($res['result'], true);
            Log::info('im发送消息返回 ：', $res);
            if ($res['ActionStatus'] == "OK") {
                return true;
            }
            return false;
        } catch (\Exception $e) {
            Log::error('im发送消息失败 ：' . $e->getMessage());
            return false;
        }
    }

}
